package com.wanlian.router.ui.me;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.smart.android.image.ImageLoader;
import com.smart.android.ui.BaseFragment;
import com.smart.android.ui.app.IntentExtra;
import com.smart.android.ui.web.WebActivity;
import com.wanlian.router.BuildConfig;
import com.wanlian.router.GlobalInfo;
import com.wanlian.router.R;
import com.wanlian.router.app.AppConfig;
import com.wanlian.router.bean.Config;
import com.wanlian.router.bean.MessageCount;
import com.wanlian.router.bean.User;
import com.wanlian.router.bean.VersionInfo;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.storage.AppData;
import com.wanlian.router.ui.dialog.UpgradeDialog;
import com.wanlian.router.ui.dialog.UpgradeDownDialog;
import com.wanlian.router.ui.integral.IncomeDetailActivity;
import com.wanlian.router.ui.login.LoginActivity;
import com.wanlian.router.ui.me.message.MessageCenterActivity;
import com.wanlian.router.widget.PieChart;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Hyu on 2018/8/29.
 * Email: fvaryu@qq.com
 */
public class MineFragment extends BaseFragment implements UpgradeDialog.OnUpgradeClickListener {
    @BindView(R.id.image_avatar)
    ImageView mAvatar;
    @BindView(R.id.tv_nickname)
    TextView mNickName;


    @BindView(R.id.tv_message_count)
    TextView mMessageCount;
    @BindView(R.id.tv_router_count)
    TextView mRouterCount;
    @BindView(R.id.tv_new_version)
    TextView tv_new_version;

    private VersionInfo mVersionInfo;

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    protected int layout() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
    }

    @Override
    protected void initData(View view) {
        super.initData(view);


        try {
            VersionInfo info = new Gson().fromJson(AppData.DEFAULT.get(AppConfig.APP_VERSION_ANDROID), VersionInfo.class);
            if (BuildConfig.VERSION_NAME.equals(info.getVersionCode())) {
                tv_new_version.setText("已是最新版本");
            }else {
                tv_new_version.setText("发现新版本");
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        NetWorkingClient.getInstance().queryMessageCount(getActivity(), new INetCallBack<MessageCount>() {
            @Override
            public void onFinish(ResponseData response, @Nullable MessageCount messageCount) {
                if (response.isSuccess()) {
                    if (messageCount != null) {
                        mMessageCount.setVisibility(messageCount.getCount() > 0 ? View.VISIBLE : View.GONE);
                    }
                }
            }
        });

        NetWorkingClient.getInstance().userInfo(getActivity(), new INetCallBack<User>() {
            @Override
            public void onFinish(ResponseData response, @Nullable User user) {
                if (response.isSuccess()) {
                    if (user == null) {
                        return;
                    }
                    GlobalInfo.getInstance().setUser(user);
                    user = GlobalInfo.getInstance().getUser();
                    ImageLoader.loadCircle(getActivity(), user.getHeadImg(), mAvatar);
                    mNickName.setText(user.getUsername());
                    mRouterCount.setText(String.format(Locale.getDefault(), "%d台", user.getDevCount()));
                }
            }
        });

    }

    @OnClick(R.id.rl_user)
    void user() {
        redirectActivity(UserProfileActivity.class);
    }

    @OnClick(R.id.tv_income)
    void income(View v) {
        redirectActivity(IncomeDetailActivity.class);
    }

    @OnClick(R.id.tv_message)
    void message() {
        Bundle bundle = new Bundle();
        bundle.putBoolean(IntentExtra.EXTRA_BOOL, mMessageCount.getVisibility() == View.VISIBLE);
        redirectActivity(MessageCenterActivity.class, bundle);
    }

    @OnClick(R.id.tv_feedback)
    void feedback() {
        redirectActivity(FeedbackActivity.class);
    }

    @OnClick(R.id.rl_my_device)
    void device() {
        redirectActivity(MyDeviceActivity.class);
    }

    @OnClick(R.id.tv_protocol)
    void protocol() {
        WebActivity.fire(getActivity(), AppData.DEFAULT.get(AppConfig.USER_PROTOCOL));
    }

    @OnClick(R.id.tv_help)
    void help() {
        WebActivity.fire(getActivity(), AppData.DEFAULT.get(AppConfig.HELP_CENTER));
    }

    @OnClick(R.id.tv_about)
    void about() {
        WebActivity.fire(getActivity(), AppData.DEFAULT.get(AppConfig.ABOUT_US));
    }

    @OnClick(R.id.tv_logout)
    void logout() {
        new AlertDialog.Builder(getActivity())
                .setMessage("确定退出登录?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        NetWorkingClient.getInstance().logout(getActivity(), new INetCallBack() {
                            @Override
                            public void onFinish(ResponseData response, @Nullable Object o) {
                                GlobalInfo.getInstance().getUserData().clean();
                                redirectActivity(LoginActivity.class);
                                getActivity().finish();
                            }
                        });
                    }
                })
                .setNegativeButton("取消", null).create().show();
    }


    @OnClick(R.id.tv_version)
    void version() {
        NetWorkingClient.getInstance().queryConfig(getActivity(),true, new INetCallBack<List<Config>>() {
            @Override
            public void onFinish(ResponseData response, @Nullable List<Config> configs) {
                if (response.isSuccess()) {
                    if (configs != null) {
                        String versionInfo = null;
                        for (Config config : configs) {
                            if(TextUtils.isEmpty(config.getCkey()) || TextUtils.isEmpty(config.getCvalue())) {
                                continue;
                            }
                            if (AppConfig.APP_VERSION_ANDROID.equals(config.getCkey())) {
                                versionInfo = config.getCvalue().trim();
                            }
                            AppData.DEFAULT.put(config.getCkey().trim(), config.getCvalue().trim());
                        }


                        try {
                             mVersionInfo = new Gson().fromJson(versionInfo, VersionInfo.class);
                            if (!BuildConfig.VERSION_NAME.equals(mVersionInfo.getVersionCode())) {
                                UpgradeDialog dialog = new UpgradeDialog(getActivity());
                                dialog.setOnUpgradeClickListener(MineFragment.this);
                                dialog.setForceUpdate("true".equals(mVersionInfo.getIsForceUpdata()));
                                dialog.setUpgradeLog(mVersionInfo.getUpdateLog().replace(";", "\n"));
                                dialog.show();
                            }else {
                                showToast("暂无新版本");
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        });
    }

    @Override
    public void onUpgradeClick(Dialog dialog, int which) {
        if (which == 0) {
            dialog.dismiss();
            if (mVersionInfo != null) {
                AppData.DEFAULT.setIgnoreVersion(mVersionInfo.getVersionCode());
            }
        }else {
            if (TextUtils.isEmpty(mVersionInfo.getDownUrl()) || !mVersionInfo.getDownUrl().endsWith(".apk")) {
                showToast("无效下载地址:" + mVersionInfo.getDownUrl());
                return;
            }
            dialog.dismiss();
            UpgradeDownDialog upgradeDownDialog = new UpgradeDownDialog(getActivity());
            upgradeDownDialog.show();
            upgradeDownDialog.start(mVersionInfo.getDownUrl());
        }
    }
}
